﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace auxiliary_proj
{
    public partial class FormViewPODetails : Form
    {
        public FormViewPODetails()
        {
            InitializeComponent();
        }

        bool isError = false;
        bool formLoad = false;

        public FormViewPODetails(DataGridViewRow row)
        {
            InitializeComponent();
            
            lblPO_ID.Text = row.Cells["PO_number"].Value.ToString();
            lblDate.Text = ((DateTime)row.Cells["timestamp"].Value).ToString("D");
            lblVendor.Text = row.Cells["vendor_id"].Value.ToString();
            lblCreatedBy.Text = row.Cells["createdBy"].Value.ToString();


            Query.populateHashtable("VENDORCODE_DESC", "WHERE vendor_id='" + lblVendor.Text + "' ");
            Query.populateHashtable("VENDORCODE_ITEMID", "WHERE vendor_id='" + lblVendor.Text + "' ");

            DataTable res = Query.select("SELECT i.vendorCode AS vendor_code, i.description AS description, poi.quantity AS quantity, poi.price AS price FROM ITEM as i, po_item AS poi WHERE poi.item_id = i.item_id AND PO_number ='" + lblPO_ID.Text + "' ORDER BY description");
            
            foreach (DataRow row2 in res.Rows)
            {
                PODataGridView.Rows.Add(row2[0], row2[1], row2[2], row2[3], "True");
            }
            PODataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
            
            formLoad = true;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            isError = false;

            foreach (DataGridViewRow row in PODataGridView.Rows)
                row.ErrorText = "";

            List<String> partialQuery = new List<String>();

                //holds [vendorCode],[quantity],[price] to later build INSERT when obtaining PO #

                //run through each row, ignore rows with [empty, NaN, or 0 quantity/price]
                foreach (DataGridViewRow row in PODataGridView.Rows)
                {
                    //if quantity or price is null (cell content is null when empty), skip
                    if (row.Cells["Quantity"].Value == null || row.Cells["Price"].Value == null)
                    {
                        row.ErrorText = "Invalid Row Data!";
                        isError = true;
                        continue;
                    }

                    int quantity;
                    bool tryQuantity = int.TryParse(row.Cells["Quantity"].Value.ToString(), out quantity);
                    float price;
                    bool tryPrice = float.TryParse(row.Cells["Price"].Value.ToString(), out price);
                    //quantity and price were converted to respective data types fine
                    if (tryQuantity && tryPrice)
                    {
                        //both are valid data types, but also need to be greater than 0
                        if (quantity > 0 && price > 0)
                        {
                            partialQuery.Add(row.Cells["vendor_code"].Value.ToString() + "," + quantity + "," + price + "," + row.Cells["UpdateAvgPrice"].Value);
                        }
                        else
                        {
                            row.ErrorText = "Invalid Row Data!";
                            isError = true;
                        }
                    }
                    else
                    {
                        row.ErrorText = "Invalid Row Data!";
                        isError = true;
                    }
                }   

            //only create PO if partialQuery list has atleast 1 value
            if (partialQuery.Count > 0 && !isError)
            {

                if (MessageBox.Show("Are you sure you want to submit this Purchase Order?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    //run through partialQuery and create insert for each result
                    foreach (string s in partialQuery)
                    {
                        Console.Out.WriteLine(partialQuery);
                        string[] split = s.Split(',');
                        Console.Out.WriteLine(split.ToString());
                        string itemID = Query.VENDORCODE_ITEMID[split[0]].ToString();
                        string itemQuantity = split[1].ToString();
                        string itemPrice = split[2].ToString();
                        
                        //query to insert item_quantity the actual items inserted (timestamp column is CURRENT_TIMESTAMP
                        string q2 = "INSERT INTO item_quantity (item_id, quantity, price) VALUES('" + itemID + "','" + itemQuantity + "','" + itemPrice + "')";
                        Console.Out.WriteLine(q2);
                        Query.nonQuery(q2);

                        //if checkbox is checked, update actual price using AVG concept detailed in 
                        if (split[3].ToString().Equals("True"))
                        {
                            //get all entries for specified itemID
                            DataTable res = Query.select("SELECT price, quantity, timestamp FROM ITEM_QUANTITY where item_id = '" + itemID + "' order by timestamp DESC");

                            //update actual price using average method on res DataTable
                            Query.nonQuery("UPDATE ITEM SET actual_price = '" + UCPurchaseOrder.average(res) + "' WHERE item_id = '" + itemID + "'");
                        }   
                    }                   

                    //Insert the PO, requeries the results in the main tab and set focus to that tab.
                    MainForm myForm = Singleton.getMainForm();
                    //enables the PO tab on the main form
                    myForm.ucPurchaseOrderSubmit = 1;
                    Query.nonQuery("UPDATE purchase_order SET status='1' WHERE PO_number='"+lblPO_ID.Text+"'");

                    DataTable results = Query.select("SELECT * FROM purchase_order where status = '0' order by timestamp ASC");
                    Singleton.getMainForm().MainPODataGridView.DataSource = results;

                    this.Dispose();
                    closeWindows();
                }

                //on submit, it will prompt the user that the information inserted will populate the DB, 
                //on yes, it inserts, no returns to the screen

                //print will create new Form with relevent print data only (only used to print, then auto dispose)
            }
            else
            {
                MessageBox.Show("Quantity and Price must be valid for each row before continuing!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void closeWindows()
        {
            //this form is closing, also close children (FormChangePass, )
            List<Form> close = new List<Form>();

            foreach (Form f in Application.OpenForms)
            {
                if (f is FormViewPO)
                    close.Add(f);
            }

            foreach (Form f in close)
            {
                f.Close();
                f.Dispose();
            }
        }

        private void po_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (formLoad)
            {
                DataGridViewCell test = PODataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                if (test.Value == null)
                {
                    MessageBox.Show("Input must not be empty!");
                }
                else
                {
                    if (test.OwningColumn.DataPropertyName.Equals("price") || test.OwningColumn.DataPropertyName.Equals("quantity"))
                    {
                        Console.Out.WriteLine("1: " + PODataGridView.Columns[e.ColumnIndex].DataPropertyName);
                        Console.Out.WriteLine("2: " + PODataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                        Console.Out.WriteLine("3: " + Query.VENDORCODE_ITEMID[PODataGridView.Rows[e.RowIndex].Cells["vendor_code"].Value].ToString());

                        string update = "UPDATE po_item SET " + PODataGridView.Columns[e.ColumnIndex].DataPropertyName + " = '" + PODataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value +
                                          "' WHERE PO_number = '" + lblPO_ID.Text + "' AND item_id = '" + Query.VENDORCODE_ITEMID[PODataGridView.Rows[e.RowIndex].Cells["vendor_code"].Value].ToString() + "'";
                        Query.nonQuery(update);
                    }
                }
            }
        }
    }
}
